<template>
  <div class="app-container">
    <!-- 操作 -->
    <div class="crud">
      <div>
        <el-button v-if="role_list.indexOf('80000090201') != -1" class="fill-btn" @click="handleUpdate(-1, 'create')">添加
        </el-button>
        <el-button v-if="role_list.indexOf('80000090203') != -1" class="plain-btn" @click="handleDelmultip">删除
        </el-button>
      </div>
      <div class="search">
        <el-input v-model="listQuery.keyword" placeholder="查找角色" class="crud-input">
          <el-button class="search-btn" slot="append" icon="el-icon-search" @keyup.enter.native="handleFilter"
            @click="handleFilter" />
        </el-input>
      </div>
    </div>

    <!-- 0 table表格 -->
    <el-form ref="RoleManagementFrom" :model="RoleManagementFrom" :rules="rules">
      <el-table :key="tableKey" v-loading="listLoading" element-loading-text="数据加载中"
        element-loading-spinner="el-icon-loading" :data="RoleManagementFrom.list" border fit highlight-current-row
        style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="expand" width="55">
          <template slot-scope="{ row }">
            <el-row v-for="(item, index) in row.check_menu" :key="item.id"
              :class="['expand-row', 'bdbom', index == 0 ? 'bdtop' : '']">
              <!-- 渲染一级权限 功能菜单 -->
              <el-col :span="5">
                <el-tag closable @close="rmPermMenu(row, item.id, 1)">{{
                  item.label
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <!-- 渲染二级和三级权限 功能菜单 -->
              <el-col :span="19">
                <el-row v-for="(item2, index2) in item.children" :key="item2.id"
                  :class="['expand-row', index2 == 0 ? '' : 'bdtop']">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="rmPermMenu(row,item2.id,2, [item.id], [item.children.length])">{{ item2.label }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable
                      @close="rmPermMenu(row, item3.id,3, [item.id, item2.id], [item.children.length, item2.children.length])">{{ item3.label }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <div>{{ row.d }}</div>
          </template>
        </el-table-column>

        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="55" label="序号" />
        <el-table-column label="角色名称" align="center" prop="name">
          <template slot-scope="{ row, $index }">
            <el-form-item v-if="row.edit_inline" :prop="'list.' + $index + '.name'" :rules="rules.name">
              <el-input v-model="row.name" class="edit-input" size="small" />
            </el-form-item>
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="设为模板" class-name="status-col" width="150">
          <template slot-scope="{ row }">
            <el-form-item v-if="row.edit_inline">
              <el-switch v-model="row.isTemplate" v-if="row.edit_inline" active-text="是" inactive-text="否"
                :active-value="1" :inactive-value="0" />
              <span v-else>{{ row.isTemplate == 0 ? "否" : "是" }}</span>
            </el-form-item>
            <div v-else>
              <el-switch v-model="row.isTemplate" v-if="row.edit_inline" active-text="是" inactive-text="否"
                :active-value="1" :inactive-value="0" />
              <span v-else>{{ row.isTemplate == 0 ? "否" : "是" }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" prop="createTime" min-width="100px" sortable align="center">
          <template slot-scope="{ row }">
            <el-form-item v-if="row.edit_inline">
              <span>{{
                row.createTime | parseTime("{y}-{m}-{d} {h}:{i}")
              }}</span>
            </el-form-item>
            <div v-else>
              <span>{{
                row.createTime | parseTime("{y}-{m}-{d} {h}:{i}")
              }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="修改时间" min-width="100px" align="center">
          <template slot-scope="{ row }">
            <el-form-item v-if="row.edit_inline">
              <span>{{
                row.updateTime | parseTime("{y}-{m}-{d} {h}:{i}")
              }}</span>
            </el-form-item>
            <div v-else>
              <span>{{
                row.updateTime | parseTime("{y}-{m}-{d} {h}:{i}")
              }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="130px" align="center">
          <template slot-scope="{ row }">
            <el-form-item v-if="row.edit_inline">
              <el-input v-model="row.remark" class="edit-input" size="small" :maxlength="120" type="textarea"
                placeholder="请输入内容" show-word-limit />
            </el-form-item>
            <span v-else>{{ row.remark }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="150px" class-name="small-padding fixed-width">
          <template slot-scope="{ row }">
            <template v-if="row.edit_inline">
              <span v-if="row.edit_inline" class="action action-update" @click="cancelEditLine(row)">取消</span>
              <span> | </span>
              <span v-if="row.edit_inline" class="action action-update" @click="updateDataInline(row)">保存</span>
            </template>
            <template v-else-if="role_list.indexOf('80000090202') != -1">
              <span class="action action-update" @click="row.edit_inline = !row.edit_inline">编辑</span>
              <span> | </span>
              <span class="action action-perm" @click="handleUpdate(row, 'update')">分配权限</span>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />

    <!-- 1 添加的弹出框 -->
    <el-dialog title="添加角色" class="created-dialog" :visible.sync="dialogFormVisible" width="60%"
      :close-on-click-modal="false" @close="cancelAddRole()">
      <el-form ref="dataForm" :model="temp" :rules="rules" label-width="90px" label-position="right">
        <div class="base-container">
          <div class="base-info">
            <div class="qn-title">
              <i class="qn-icon-flag"></i>
              <span>基本信息</span>
            </div>
            <div class="qn-content">
              <div class="qn-part">
                <el-form-item class="qn-icon-require" prop="name" size="small">
                  <span slot="label" class="form-item-label">角色名称</span>
                  <el-input class="qn-role-input" placeholder="请输入角色名称" v-model="temp.name"></el-input>
                </el-form-item>
              </div>
              <div class="qn-part">
                <el-form-item label="备注:" size="small">
                  <el-input class="qn-role-textarea" type="textarea" :maxlength="120" :row="6" resize="none"
                    placeholder="请输入备注信息" v-model="temp.remark" show-word-limit></el-input>
                </el-form-item>
              </div>
              <div class="select-template">
                <span>是否设为模板: </span>
                <!-- <el-switch v-model="value" active-color="#13ce66" inactive-color="#ff4949"> </el-switch> -->
                <el-radio v-model="temp.isTemplate" :label="1">是</el-radio>
                <el-radio v-model="temp.isTemplate" :label="0">否</el-radio>
              </div>
            </div>
          </div>

          <div class="base-btn">
            <el-button class="plain-dialog-btn" @click="cancelAddRole()">取消</el-button>
            <el-button class="fill-dialog-btn" @click="createdData">保存</el-button>
          </div>
        </div>
        <!-- 分割线 -->
        <div class="qn-line"></div>

        <!-- 分配权限 -->
        <div class="distribute-container">
          <div class="qn-title">
            <i class="qn-icon-flag"></i>
            <span>权限配置</span>
            <i class="qn-tj">已添加{{ add_total }}个功能权限</i>

            <div class="perm-template">
              <span>角色模板: </span>
              <el-select v-model="role_id" filterable reserve-keyword placeholder="选择模板" clearable @change="roleChange">
                <el-option v-for="item in list_role" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </div>
          </div>
          <el-tree :data="all_tree" show-checkbox node-key="id" default-expand-all ref="addrole_tree"
            :props="defaultProps" :default-checked-keys="checked_role" @check-change="addCheckChange">
          </el-tree>
        </div>
      </el-form>
    </el-dialog>

    <!-- 2 分配权限的弹出框 (修改) -->
    <el-dialog title="修改角色" class="update-dialog" :visible.sync="dialogTreeVisible" width="60%" center
      :close-on-click-modal="false" @close="cancelEditRole">
      <div class="menu-title">
        <i class="qn-icon-flag"></i>
        <span>关联用户</span>
        <i class="qn-tj">已关联{{ (temp.userList && temp.userList.length) || 0 }}个用户</i>
      </div>
      <div class="related-user">
        <el-tag class="user-item" v-for="(user, index) in temp.userList" :key="user.id" type="success" closable
          @close="rmRoleUser(index)">
          {{ user.name }}
        </el-tag>
      </div>

      <div class="menu-title">
        <i class="qn-icon-flag"></i>
        <span>菜单权限</span>
        <i class="qn-tj" v-show="update_total != 0">已选择{{ update_total }}个功能权限</i>
      </div>
      <el-tree :data="all_tree" show-checkbox node-key="id" default-expand-all :default-checked-keys="temp.check_menuID"
        :props="defaultProps" ref="updaterole_tree" @check-change="updateCheckChange">
      </el-tree>
      <!-- <div>{{temp.check_menuID}}</div> -->

      <div slot="footer" class="dialog-footer">
        <el-button class="plain-dialog-btn" @click="dialogTreeVisible = false">取消</el-button>
        <el-button class="fill-dialog-btn" @click="updateData()">确认</el-button>
      </div>
    </el-dialog>

    <!-- 3 删除的提示框 -->
    <el-dialog :visible.sync="dialogPvVisible" title="提示" width="30%" center>
      <div class="del-data del-img">
        <img :src="require('../../assets/img/del.png')" alt="" />
      </div>
      <div class="del-data del-notify">确定对角色进行【删除】？</div>
      <span slot="footer" class="dialog-footer">
        <el-button class="plain-dialog-btn" @click="dialogPvVisible = false">取消</el-button>
        <el-button class="fill-dialog-btn" @click="delData">确认</el-button>
      </span>
    </el-dialog>
    <!-- 4 状态更改的提示框 -->
    <el-dialog :visible.sync="dialogToggle" title="提示" width="30%" center>
      <div class="del-data del-img">
        <img :src="require('../../assets/img/remind.png')" alt="" />
      </div>
      <div class="del-data del-notify">确定对角色进行【更改】？</div>
      <span slot="footer" class="dialog-footer">
        <el-button class="plain-dialog-btn" @click="handleCancel(sta_row)">取消</el-button>
        <el-button class="fill-dialog-btn" @click="toggleStatus(sta_row)">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import waves from "@/directive/waves"; // waves directive
  import {
    parseTime
  } from "@/utils"; // 解析时间
  import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
  import {
    roleList,
    roleMenutree,
    roleExist,
    roleUpdate,
    roleDel,
    roleBinduser,
    roleUsers,
    rolePermid,
    userSelectRole,
  } from "@/api/permission";
  import {
    validPass
  } from "@/utils/validate";
  import {
    logger
  } from "runjs/lib/common";
  import {
    editRole
  } from "@/api/system";
  const calendarTypeOptions = [{
      key: "CN",
      display_name: "China"
    },
    {
      key: "US",
      display_name: "USA"
    },
    {
      key: "JP",
      display_name: "Japan"
    },
    {
      key: "EU",
      display_name: "Eurozone"
    },
  ];

  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name;
    return acc;
  }, {});

  export default {
    name: "PermissionRole",
    components: {
      Pagination
    },
    directives: {
      waves
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: "success",
          draft: "info",
          deleted: "danger",
        };
        return statusMap[status];
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type];
      },
    },
    data() {
      const validatePassword = (rule, value, callback) => {
        // if (!validPass(value) && (value && value.length != 64)) {
        if (!validPass(value)) {
          callback(new Error("8~16位,包含大小写字母和数字, 可以有特殊字符"));
        } else {
          callback();
        }
      };

      const validateRoleName = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入角色名称！"));
        } else {
          const reg = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
          if (value.length > 20 || !reg.test(value)) {
            callback(
              new Error("请输入1～20个字，角色名只允许中英文、数字和下划线！")
            );
          } else {
            callback();
          }
        }
      };

      return {
        multipleSelection: [],
        is_multip: false, // 是否批量删除
        tableKey: 0,

        RoleManagementFrom: {
          list: [],
        },
        total: 0, // 总条数
        listLoading: true,
        listQuery: {
          page: 1, // 第几页
          limit: 10, // 每页显示的条数row
          keyword: "", // 搜索关键字
        },
        calendarTypeOptions,
        temp: {
          id: "",
          name: "", // 角色名
          remark: "", // 备注
          check_menuID: [], // 当前角色 默认勾选的权限id列表,
          menu: [{
            appCode: 80000,
            checked: []
          }],
          relatedUser: "", // 该角色绑定的用户
          isTemplate: 0,
          userList: [], // 该角色关联的用户
        },
        temp_row: null,
        all_tree: [], // 当前登录者 角色所拥有的 功能权限菜单
        add_total: 0,
        update_total: 0,

        dialogFormVisible: false,
        dialogStatus: "",
        dialogTreeVisible: false,
        defaultProps: {
          // tree 配置项
          children: "children",
          label: "label",
        },
        del_id: "",
        del_index: null,
        dialogPvVisible: false, // 删除提示框
        dialogToggle: false, // 状态更改的提示框

        list_role: [], // 角色列表
        role_id: "", // 角色模板ID
        checked_role: [], // 创建角色时选择默认模板
        sta_row: {}, // 修改状态值, 保存当前数据

        rules: {
          name: [{
            required: true,
            trigger: "blur",
            validator: validateRoleName
          }, ],
          password: [{
            required: true,
            trigger: "blur",
            validator: validatePassword
          }, ],
          userName: [{
            required: true,
            trigger: "blur",
            validator: validatePassword
          }, ],
          again_pass: [{
            required: true,
            trigger: "blur",
            validator: validatePassword
          }, ],
        },
        role_list: [], // 按钮权限
      };
    },
    watch: {
      // dialogFormVisible: {
      //   handler(val, oldval) {
      //     if (val) {
      //       this.getListRole() // 获得角色列表
      //     }
      //   }
      // }
    },
    created() {
      this.getList();
    },
    mounted() {
      this.getPermsMenu();
      this.getRoleList();
      this.role_list = this.$store.getters.menu_code_list;
    },
    computed: {
      theme() {
        return this.$store.state.settings.theme;
      },
    },
    methods: {
      // 获取 table 列表
      getList() {
        this.listLoading = true;
        roleList({
            pageNo: this.listQuery.page,
            pageSize: this.listQuery.limit,
            name: this.listQuery.keyword,
          })
          .then((res) => {
            if (res.code == 0) {
              this.RoleManagementFrom.list = res.list;

              this.RoleManagementFrom.list = this.RoleManagementFrom.list.map(
                (item, i) => {
                  function filterItem(arr) {
                    // 自定义 数组过滤函数: 只保留当前勾选的权限菜单
                    let newarr = arr.filter((item2, index, arr2) => {
                      if (item2.children && item2.children.length != 0) {
                        item2.children = filterItem(item2.children)
                      }
                      return item.menuTree[0].checked.indexOf(item2.id) != -1
                    })

                    return newarr
                  }
                  item.check_menu = filterItem(item.menuTree[0].data)
                  console.log('处理前的权限 :>> ', item.menuTree[0].checked)
                  console.log('处理后的权限 :>> ', item.check_menu)

                  let onlyleaf = []
                  // 选中的节点中, 只筛选叶子节点
                  function filterLeaf(arr) {

                    arr.map((val,index) => {
                      if(val.children && val.children.length != 0) {
                        filterLeaf(val.children)
                      }
                      else if(val.children && val.children.length == 0){
                        if(val.id) onlyleaf.push(val.id)
                      }
                    })
                  }
                  filterLeaf(item.check_menu);

                  // item.check_menuID = item.menuTree[0].checked;
                  item.check_menuID = onlyleaf
                  // console.log(item.check_menuID)
                  item.original_userList = [...item.userList];
                  this.$set(item, "edit_inline", false);
                  item.original_name = item.name;
                  item.original_remark = item.remark;
                  item.original_isTemplate = item.isTemplate;
                  return item;
                }
              );

              this.total = parseInt(res.total);
              this.listLoading = false;
            } else {
              this.$message({
                message: "请求失败",
                type: "error",
              });
            }
          })
          .catch(() => {
            this.$message({
              message: "网络错误",
              type: "error",
            });
          });
      },
      // 取消当行编辑
      cancelEditLine(row, is_cancel = true) {
        row.name = row.original_name;
        row.remark = row.original_remark;
        row.isTemplate = row.original_isTemplate;
        row.edit_inline = false;
        if (is_cancel)
          this.$message({
            message: "已经取消更改",
            type: "warning",
          });
      },
      // 行内编辑提交更新请求
      updateDataInline(row) {
        this.$refs["RoleManagementFrom"].validate((valid) => {
          if (valid) {
            row.menu = JSON.stringify(row.menuTree);
            if (row.userList) {
              let arr = [];
              row.userList.forEach((item, i) => {
                arr.push(item.id);
              });
              row.relatedUser = arr.toString();
            }

            roleUpdate(row)
              .then((res) => {
                if (res.code == 0) {
                  // const index = this.list.findIndex(v => v.id === this.temp.id) // 找到被更改的item下标
                  // this.list.splice(index, 1, this.temp) // 通过下标更改list的数据
                  this.getList();
                  // this.resetfilter()
                  row.edit_inline = false;
                  this.$notify({
                    title: "成功",
                    message: "更新成功",
                    type: "success",
                    duration: 4000,
                  });
                } else {
                  this.cancelEditLine(row, false);
                  this.$message({
                    message: "更改失败",
                    type: "error",
                  });
                }
              })
              .catch((res) => {
                this.cancelEditLine(row, false);
                this.$message({
                  message: "更改失败!",
                  type: "error",
                });
              });
          }
        });
      },
      // 点击了 状态值切换==========================
      changeStatus(row) {
        this.dialogToggle = true;
        this.sta_row = row;
      },
      // 确认了  状态值切换
      toggleStatus(row) {
        roleUpdate(row)
          .then((res) => {
            this.$notify({
              title: "成功",
              message: "状态修改成功",
              type: "success",
              duration: 4000,
            });
            this.getRoleList();
            this.dialogToggle = false;
          })
          .catch((res) => {
            this.cancelEditLine(row);
            this.$message({
              message: "网络错误",
              type: "error",
            });
          });
      },
      // 取消状态管理
      handleCancel(row) {
        this.cancelEditLine(row);
        this.dialogToggle = false;
      },

      // 删除了某项权限 功能菜单
      async rmPermMenu(row, menuId, level, parent, len) {
        const result = await this.$confirm(
          "此操作将删除该权限, 是否继续?",
          "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            center: true,
          }
        ).catch((err) => {});

        if (result == "cancel") {
          return this.$message({
            message: "删除已取消",
            type: "warning",
          });
        }
        else if (result == "confirm") {
          let tempMenuId = ''   // 根据父级的children的个数, 决定删除哪个id
          if(level==3 && len[0] == 1 && len[1] == 1){
            tempMenuId = parent[0]
          }
          else if(level==3 && len[0] != 1 && len[1] == 1) {
            tempMenuId = parent[1]
          }
          else if(level==2 && len[0] == 1){
            tempMenuId = parent[0]
          }
          else {
            tempMenuId = menuId
          }
          // 发送删除该权限的网络请求
          function delRole() {}

          rolePermid({
              roleId: row.id,
              menuId: tempMenuId
            })
            .then((res) => {
              if (res.code == 0) {
                this.$message({
                  message: "删除权限成功",
                  type: "success",
                });
                this.getList();
                // row.children = res.data
              } else {
                this.$message({
                  message: "删除权限失败",
                  type: "error",
                });
              }
            })
            .catch((res) => {
              this.$message({
                message: "网络错误",
                type: "error",
              });
            })
        }
      },
      // 获取当前登录者的角色, 所拥有的权限菜单
      getPermsMenu() {
        roleMenutree()
          .then((res) => {
            if (res.code == 0) {
              this.all_tree = res.data[0].data;
            } else {
              this.$message({
                message: "请求失败",
                type: "error",
              });
            }
          })
          .catch((res) => {
            this.$message({
              message: "网络错误",
              type: "error",
            });
          });
      },

      // 给角色分配权限时, 所选的权限树, 数量变化
      updateCheckChange() {
        this.update_total =
          this.$refs["updaterole_tree"].getCheckedKeys(false).length || 0; // false 包含半选状态的
      },
      // 新增角色时, 所选的权限树, 数量变化
      addCheckChange() {
        this.add_total =
          this.$refs["addrole_tree"].getCheckedKeys(false).length || 0; // false 包含半选状态的
      },
      // 点击了 '分配权限' 或 '添加' ======================================================
      handleUpdate(row, str) {
        if (str == "create") {
          // console.log(this.checked_role);
          this.resetTemp(); // 清空
          this.dialogFormVisible = true;
          this.$nextTick(() => {
            this.$refs["dataForm"].clearValidate();
          });
        } else if (str == "update") {
          this.temp = Object.assign({}, row); // 克隆一个对象
          this.temp_row = row;

          this.temp.menu = [{
            appCode: 80000,
            checked: []
          }];
          this.temp.relatedUser = "";
          this.dialogTreeVisible = true;
        }
        this.dialogStatus = str;
      },
      // 取消修改角色
      cancelEditRole() {
        this.$refs["updaterole_tree"].setCheckedKeys([]);
        this.temp_row.userList = [...this.temp.original_userList];
        this.getList() // 优化:  用本地存储解决
      },
      // 取消添加角色
      cancelAddRole() {
        // console.log(this.$refs["addrole_tree"]);
        this.$refs["addrole_tree"].setCheckedKeys([]);
        // this.checked_role.splice()
        this.checked_role = [];
        // console.log(this.checked_role);
        this.dialogFormVisible = false;
      },

      // 编辑: 确认更新数据
      updateData() {
        this.temp.menu[0].checked =
          this.$refs["updaterole_tree"].getCheckedKeys().concat(this.$refs["updaterole_tree"].getHalfCheckedKeys())
        this.temp.menu = JSON.stringify(this.temp.menu);
        if (this.temp.userList) {
          let arr = [];
          this.temp.userList.forEach((item, i) => {
            arr.push(item.id);
          });
          this.temp.relatedUser = arr.toString();
        }

        roleUpdate(this.temp).then(() => {
          // const index = this.list.findIndex(v => v.id === this.temp.id) // 找到被更改的item下标
          // this.list.splice(index, 1, this.temp) // 通过下标更改list的数据
          this.getList();
          this.getRoleList();
          this.$refs["updaterole_tree"].setCheckedKeys([]);
          this.dialogTreeVisible = false;
          this.$notify({
            title: "成功",
            message: "更新成功",
            type: "success",
            duration: 4000,
          });
        });
      },
      // 新增了角色
      createdData() {
        this.$refs["dataForm"].validate((valid) => {
          if (valid) {
            this.temp.menu[0].checked =
              this.$refs["addrole_tree"].getCheckedKeys().concat(this.$refs["addrole_tree"].getHalfCheckedKeys())
            this.temp.menu = JSON.stringify(this.temp.menu);
            roleUpdate(this.temp).then(() => {
              // const index = this.list.findIndex(v => v.id === this.temp.id) // 找到被更改的item下标
              // this.list.splice(index, 1, this.temp) // 通过下标更改list的数据
              this.getList();
              this.$refs["addrole_tree"].setCheckedKeys([]);
              this.dialogFormVisible = false;
              this.$notify({
                title: "成功",
                message: "创建成功",
                type: "success",
                duration: 4000,
              });
              this.getRoleList();
            });
          }
        });
      },

      // 清空temp
      resetTemp() {
        this.temp = {
          id: "",
          name: "", // 角色名
          remark: "", // 备注
          check_menuID: [], // 当前角色 默认勾选的权限id列表,
          menu: [{
            appCode: 80000,
            checked: []
          }],
          relatedUser: "", // 该角色绑定的用户
          isTemplate: 0,
        };
      },
      // 删除角色绑定的用户
      rmRoleUser(num) {
        this.temp.userList.splice(num, 1);
      },
      // 单个删除===============================================
      handleDelete(row, index) {
        this.is_multip = false;
        this.del_id = row.id;
        this.del_index = index;
        this.dialogPvVisible = true;
      },
      // 批量删除
      handleDelmultip() {
        if (this.multipleSelection.length == 0) {
          this.$message({
            message: "没有被选项!",
            type: "error",
            duration: 4000,
            showClose: true,
            center: true,
          });
        } else {
          this.is_multip = true;
          this.dialogPvVisible = true;
        }
      },
      // 确认了删除
      delData() {
        let ids = [];
        if (this.is_multip) {
          // 批量删
          this.multipleSelection.forEach((item, i) => {
            ids.push(item.id);
          });
        } else {
          ids = [this.del_id];
        }
        roleDel(ids).then(() => {
          this.dialogPvVisible = false;
          // this.list.splice(this.del_index, 1)
          this.getList();
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 4000,
          });
        });
      },

      // 搜索
      handleFilter() {
        this.listQuery.page = 1;
        this.getList();
      },
      // 批量选择
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 获取角色列表 (下拉回显)
      getRoleList() {
        userSelectRole({
          isTemplate: 1
        }).then((res) => {
          this.list_role = res.data || [];
        });
      },
      // 角色模板的切换
      roleChange() {
        this.RoleManagementFrom.list.forEach((item) => {
          if (item.id == this.role_id) {
            // this.checked_role = [...item.check_menuID]
            this.checked_role = item.check_menuID.slice();
          }
        });
      },
    },
  };
</script>

<style lang="scss">
  @import "~@/styles/variables.scss";

  // .crud-input {
  //   border: 0;
  //   &.el-input--medium {
  //     font-size: 12px;
  //   }
  //   &.el-input--medium .el-input__inner {
  //     height: 27px !important;
  //     background: transparent;
  //     border: 0;
  //     -webkit-appearance: none;
  //     border-radius: 3px;
  //     // padding: 12px 5px 12px 15px;
  //     color: $text_dark;
  //     caret-color: $text_dark;

  //     &:-webkit-autofill {
  //       box-shadow: 0 0 0 1000px $my_opacity inset !important;
  //       -webkit-text-fill-color: $text_dark !important;
  //     }
  //   }
  //   .el-input-group__append {
  //     color: var(--app_primary);
  //     border: 0;
  //     border-left: 1px solid var(--app_primary);

  //     .el-button {
  //       // height: 27px;
  //       // border: 1px solid $my_primary !important;
  //       // background-color: #f11;
  //     }

  //   }

  // }

  .el-dialog {
    .el-dialog__header {
      background-color: #f5f7f5 !important;
    }
  }

  .qn-role-textarea {
    .el-textarea__inner {
      height: 70px;
      font-size: 14px;
      font-weight: 400;
      background: rgba(0, 0, 0, 0.02);
      border: 1px dashed rgba(0, 0, 0, 0.15);
      border-radius: 4px;
    }
  }

  .el-form-item__label {
    // 两端对齐
    display: flex;
    justify-content: space-between;
    align-items: center !important;

    &::before {
      transform: translateY(3px);
    }

    .form-item-label {
      flex: 1;
      text-align-last: justify !important;
      text-align: justify !important;
    }
  }
</style>


<style lang="scss" scoped>
  @import "~@/styles/variables.scss";

  .app-container {
    padding: 10px;
    background-color: #ffffff;
    min-height: 750px;

    .crud {
      margin-bottom: 32px;
      display: flex;
      justify-content: space-between;

      .crud-input {
        height: 27px;
        width: 300px;
        border: 1px solid var(--app_primary);
        border-radius: 3px;
        // background-color: aqua;
      }
    }

    // background-color: #f99 !important;
    .el-table {
      .action {
        font-size: 13px;
        color: var(--app_primary);
        cursor: pointer;

        &:hover {
          text-decoration: underline;
        }
      }

      .expand-row {
        display: flex;
        align-items: center;

        .el-tag {
          margin: 7px;
        }
      }

      .bdtop {
        border-top: 1px solid #eee;
      }

      .bdbom {
        border-bottom: 1px solid #eee;
      }

      .temp-input {
        display: flex;
        flex-wrap: nowrap;
      }

      .edit-input {
        margin-right: 10px;
      }

      .cancel-btn {
        // display: inline-block;
      }
    }

    .el-dialog {
      .del-data {
        text-align: center;
        margin-bottom: 16px;

        img {
          width: 130px;
          height: 110px;
        }
      }

      .del-img {}
    }

    .created-dialog {
      .base-container {
        display: flex;
        justify-content: space-between;

        .base-info {
          width: 60%;

          .qn-title {
            margin-top: 2px;

            .qn-icon-flag {
              display: inline-block;
              width: 10px;
              height: 10px;
              background-color: var(--app_primary);
              border-radius: 50%;
              margin-right: 5px;
            }

            span {
              font-family: PingFangSC-Medium;
              font-size: 14px;
              color: rgba($my_primary, 1);
            }
          }

          .qn-content {
            // background-color: #eef;
            margin-top: 22px;

            .qn-part {
              position: relative;
              margin-top: 18px;

              .qn-role-input {
                width: 220px;
              }

              .qn-role-textarea {
                .el-textarea__inner {
                  height: 94px;
                  font-size: 14px;
                  font-weight: 400;
                  background: rgba(0, 0, 0, 0.02);
                  border: 1px dashed rgba(0, 0, 0, 0.15);
                  border-radius: 4px;
                }
              }

              .qn-note-limit {
                position: absolute;
                right: 4px;
                bottom: 4px;
                font-style: normal;
                font-family: PingFangSC-Regular;
                font-size: 14px;
                color: #9b9b9b;
              }
            }

            .select-template {
              // background-color: salmon;
            }
          }
        }
      }

      .qn-line {
        width: 100%;
        margin: 10px 0;
        border-bottom: 1px solid #e9e9e9;
      }

      .distribute-container {

        // background-color: #fee;
        .qn-title {
          // background-color: salmon;
          margin-top: 2px;

          .qn-icon-flag {
            display: inline-block;
            width: 10px;
            height: 10px;
            background-color: var(--app_primary);
            border-radius: 50%;
            margin-right: 5px;
          }

          span {
            font-family: PingFangSC-Medium;
            font-size: 14px;
            color: rgba($my_primary, 1);
          }

          .qn-tj {
            font-size: 12px;
            color: $text_light;
            line-height: 24px;
            margin-left: 20px;
          }

          .perm-template {
            display: inline-block;
            margin-left: 50px;
          }
        }
      }
    }

    .update-dialog {
      .menu-title {
        line-height: 30px;
        margin-bottom: 15px;

        .qn-icon-flag {
          display: inline-block;
          width: 10px;
          height: 10px;
          background-color: var(--app_primary);
          border-radius: 50%;
          margin-right: 5px;
        }

        span {
          color: $text_dark;
        }

        .qn-tj {
          font-size: 12px;
          color: $text_light;
          margin-left: 20px;
        }
      }

      .related-user {
        border: 1px dashed $border_light;
        padding: 10px;
        border-radius: 3px;
        background-color: #fafafa;
        margin-bottom: 20px;
        display: flex;
        flex-wrap: wrap;

        .user-item {
          margin-right: 10px;
        }
      }
    }
  }
</style>
